<script setup lang="ts">
import { ref } from 'vue';
import {useCascaderAreaData} from '@vant/area-data'
import { showToast } from 'vant';
import { addAddress } from '@/services/address';


const receiver = ref('');
const mobile = ref('');
const provinceCode = ref('')
const cityCode = ref('')
const countyCode =ref('')
const addressDetail = ref('');
const isDefault = ref(false);


const show = ref(false);
const fieldValue = ref('');
const cascaderValue = ref('');
const options = useCascaderAreaData();

type addressList = {
  text:string,
  value:string
}
const onFinish = (event:{selectedOptions:addressList[]}) => {
  show.value = false;
  fieldValue.value = event.selectedOptions.map((item,index) => {
    if(index===0) provinceCode.value = item.value
    if(index===1) cityCode.value = item.value
    if(index===2) countyCode.value = item.value
    // console.log(item.value)
    return item.text}).join('/');
  // console.log(provinceCode.value)
}

const onSubmit = async ()=>{
  if(!receiver.value) return showToast('请输入收货人姓名')
  if(!mobile.value) return showToast('请输入收货人联系电话')
  if(!provinceCode.value) return showToast('请输入收货人地址')
  if(!addressDetail.value) return showToast('请输入收货人详细地址')

  await addAddress({
    receiver:receiver.value,
    mobile:mobile.value,
    provinceCode:provinceCode.value,
    cityCode:cityCode.value,
    countyCode:countyCode.value,
    addressDetail:addressDetail.value,
    isDefault:isDefault.value ? 1 : 0
  })
  showToast('添加收货人信息成功')
  // console.log(res.data)
}
</script>

<template>
  <cp-nav-bar title="收货人信息" right-text="保存并选择" @click-right="onSubmit"></cp-nav-bar>
  <div class="user-info">
    <van-cell-group inset>
    <!-- 输入任意文本 -->
    <van-field v-model="receiver" placeholder="请输入收货人姓名" label="收货人" />
    <!-- 输入手机号，调起手机号键盘 -->
    <van-field v-model="mobile" type="tel" label="手机号" placeholder="请输入收货人手机号码"/>
    <!-- 允许输入正整数，调起纯数字键盘 -->
    <van-field
      v-model="fieldValue"
      is-link
      readonly
      label="地区"
      placeholder="请选择所在地区"
      @click="show = true"
    />
    <van-popup v-model:show="show" round position="bottom">
      <van-cascader
        v-model="cascaderValue"
        title="请选择所在地区"
        :options="options"
        @close="show = false"
        @finish="onFinish"
      />
    </van-popup>
    <!-- 允许输入数字，调起带符号的纯数字键盘 -->
    <van-field v-model="addressDetail"  placeholder="请输入收货人详细地址" label="详细地址" />
    <!-- 输入密码 -->
    <div class="check-box">
      是否设置为默认地址 <van-checkbox v-model="isDefault"></van-checkbox>
    </div>
    </van-cell-group>
  </div>
</template>

<style lang="scss">
.check-box{
  display: flex;
  justify-content: space-between;
  padding:15px;
}
.user-info{
  padding-top: 50px;
  .van-field{
    border-bottom: 1px solid #ccc;
  }
}
</style>

